import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";
import "package:ttlock_flutter/ttgateway.dart";
import "package:ttlock_flutter/ttlock.dart";

// 定义WiFi配置类型枚举
enum ConfigWifiType {
  gateway,
  lock,
}

class SelectWifi extends StatefulWidget {
  final ConfigWifiType type;
  final String? deviceData; // 设备数据，对于门锁类型需要提供

  const SelectWifi({
    super.key, 
    required this.type,
    this.deviceData,
  });

  @override
  State<StatefulWidget> createState() => _SelectWifiState();
}

class _SelectWifiState extends State<SelectWifi> {
  static _SelectWifiState? _currentInstance; // 跟踪当前活跃实例
  List _wifiList = [];
  bool _isLoading = true;

  void _setWifiList(List list) {
    print("当前实例是否为活跃实例: ${_currentInstance == this}");
    
    // 只有当前活跃实例才能更新状态
    if (mounted && _currentInstance == this) {
      setState(() {
        _wifiList = list;
        _isLoading = false;
      });
    } else {
      print("Widget已销毁或不是当前活跃实例，无法更新状态");
    }
  }

  void _getNearbyWifi() {
    print("_getNearbyWifi被调用");
    // 重置状态，确保每次扫描都从干净的状态开始
    if (mounted && _currentInstance == this) {
      setState(() {
        _wifiList = [];
        _isLoading = true;
        print("状态已重置 - _wifiList长度: ${_wifiList.length}, _isLoading: $_isLoading");
      });
    } else {
      print("Widget已销毁或不是当前活跃实例，无法重置状态");
      return;
    }
    
    try {
      switch (widget.type) {
        case ConfigWifiType.gateway:
          _getGatewayWifi();
          break;
        case ConfigWifiType.lock:
          if (widget.deviceData == null) {
            EasyLoading.showError("缺少设备数据");
            return;
          }
          _getLockWifi(widget.deviceData!);
          break;
      }
    } catch (error) {
      EasyLoading.showToast(error.toString());
      if (mounted && _currentInstance == this) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  // 获取网关WiFi列表
  void _getGatewayWifi() {
    print("开始获取网关WiFi列表");
    TTGateway.getNearbyWifi((finished, wifiList) {
      print("网关WiFi列表回调: finished=$finished, wifiList=$wifiList");
      print("wifiList类型: ${wifiList.runtimeType}");
      if (wifiList != null) {
        print("wifiList长度: ${wifiList.length}");
      }
      if (mounted && _currentInstance == this) {
        _setWifiList(wifiList ?? []);
      } else {
        print("Widget已销毁或不是当前活跃实例，无法设置WiFi列表");
      }
    }, (errorCode, errorMsg) {
      print("网关WiFi获取错误: $errorCode - $errorMsg");
      EasyLoading.showToast(errorMsg);
      if (mounted && _currentInstance == this) {
        setState(() {
          _isLoading = false;
        });
      }
    });
  }

  // 获取门锁WiFi列表
  void _getLockWifi(String lockData) {
    print("开始获取门锁WiFi列表，lockData: $lockData");
    TTLock.scanWifi(lockData, (finished, wifiList) {
      print("门锁WiFi列表回调: finished=$finished, wifiList=$wifiList");
      print("wifiList类型: ${wifiList.runtimeType}");
      if (wifiList != null) {
        print("wifiList长度: ${wifiList.length}");
      }
      if (finished) {
        if (mounted && _currentInstance == this) {
          _setWifiList(wifiList ?? []);
        } else {
          print("Widget已销毁或不是当前活跃实例，无法设置WiFi列表");
        }
      } else {
        print("门锁WiFi扫描未完成");
      }
    }, (errorCode, errorMsg) {
      print("门锁WiFi获取错误: $errorCode - $errorMsg");
      EasyLoading.showError("$errorCode: $errorMsg");
      if (mounted && _currentInstance == this) {
        setState(() {
          _isLoading = false;
        });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    print("SelectWifi initState被调用");
    
    // 设置当前实例为活跃实例
    _currentInstance = this;
    print("当前实例已设置为活跃实例");
    
    // 重置状态，确保每次进入页面都重新扫描
    _wifiList = [];
    _isLoading = true;
    print("initState中状态已重置 - _wifiList长度: ${_wifiList.length}, _isLoading: $_isLoading");
    
    // 使用Future.microtask确保在正确的时机开始WiFi扫描
    Future.microtask(() {
      if (mounted && _currentInstance == this) {
        _getNearbyWifi();
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    print("SelectWifi dispose被调用");
    
    // 如果当前实例是活跃实例，则清除引用
    if (_currentInstance == this) {
      _currentInstance = null;
      print("当前实例引用已清除");
    }
    
    EasyLoading.dismiss();
  }

  @override
  Widget build(BuildContext context) {
    print("build方法被调用 - _isLoading: $_isLoading, _wifiList长度: ${_wifiList.length}");
    
    return NormalScaffold(
      title: "选择WIFI",
      child: _isLoading 
        ? const Center(child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            CircularProgressIndicator(),
            SizedBox(height: 8,),
            Text("正在搜索wifi...")
          ],
        ))
        : _wifiList.isEmpty
          ? Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text("未找到WiFi网络", style: TextStyle(color: Colors.grey)),
                  const SizedBox(height: 20),
                  ElevatedButton(
                    onPressed: _getNearbyWifi,
                    child: const Text("重新扫描"),
                  ),
                ],
              ),
            )
          : ListView.separated(
              padding: const EdgeInsets.all(ThemeVars.paddingPage),
              itemBuilder: (context, index) {
                Map wifi = _wifiList[index];
                final rssi = wifi["rssi"] as int? ?? -100;
                
                // 根据rssi值确定信号强度图标
                IconData signalIcon;
                Color signalColor;
                if (rssi > -50) {
                  signalIcon = Icons.signal_wifi_4_bar;
                  signalColor = Colors.green;
                } else if (rssi > -70) {
                  signalIcon = Icons.network_wifi;
                  signalColor = Colors.green;
                } else if (rssi > -80) {
                  signalIcon = Icons.signal_wifi_0_bar;
                  signalColor = Colors.orange;
                } else {
                  signalIcon = Icons.signal_wifi_bad;
                  signalColor = Colors.red;
                }
                
                return GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    Stacker.pop(wifi);
                  },
                  child: DecoratedBox(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(6),
                      boxShadow: const [ThemeVars.boxShadow],
                      color: Colors.white,
                    ),
                    child: Container(
                      padding: const EdgeInsets.all(16),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(wifi["wifi"], style: const TextStyle(fontSize: 18)),
                                Text(
                                  rssi > -70 ? "信号强" : "信号弱", 
                                  style: TextStyle(color: signalColor),
                                ),
                              ],
                            ),
                          ),
                          Icon(signalIcon, color: signalColor),
                        ],
                      ),
                    ),
                  ),
                );
              },
              separatorBuilder: (context, index) => const SizedBox(height: 12),
              itemCount: _wifiList.length,
            ),
    );
  }
} 